﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using static UnityEngine.GraphicsBuffer;

public enum GamePhase
{
    gameStart, playerDraw, playerAction, enemyDraw, enemyAction
}

public class BattleManager : MonoSingleton<BattleManager>
{
    public new static BattleManager Instance { get; private set; }
    public PlayerData playerData;
    public PlayerData enemyData;
    //数据
    public List<Card> playerDeckList = new List<Card>();
    public List<Card> playerDeckList2 = new List<Card>();
    public List<Card> enemyDeckList = new List<Card>();
    //弃牌堆
    public List<Card> playerDiscardPile = new List<Card>();
    public List<Card> playerDiscardPile2 = new List<Card>();
    public List<Card> enemyDiscardPile = new List<Card>();
    //卡组
    public GameObject cardPrefab;
    //卡牌
    public Transform playerHand;
    public Transform playerHand2;
    public Transform enemyHand;
    //手牌
    public GameObject[] playerBlocks;
    public GameObject[] enemyBlocks;
    //格子
    public GameObject playerIcon;
    public GameObject playerIcon2;
    public GameObject enemyIcon;

    //攻击目标
    public AttackTarget playerAttackTarget;
    public AttackTarget playerAttackTarget2;
    public AttackTarget enemyAttackTarget;

    public GamePhase GamePhase = GamePhase.gameStart;
    //事件系统
    public UnityEvent phaseChangeEvent = new UnityEvent();
    private GameObject arrow;

    public Transform Canvas;

    private GameObject attackingcard;
    private int attackingPlayer;
    public GameObject attackArrow;
    // Start is called before the first frame update
    private new void Awake()
    {
        Instance = this;
    }
    void Start()
    {
        GameStart();
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(1))
        {
            DestroyArrow();
            CloseBlocks();
        }
    }
    //游戏流程
    //开始游戏：加载数据,卡组洗牌，初始手牌
    //回合结束：游戏阶段

    public void GameStart()
    {
        //读取数据
        ReadDeck();
        //卡组洗牌
        ShuffletDeck(0);
        ShuffletDeck(1);
        //玩家抽卡3，敌人抽卡3
        //DrawCard(0, 4);
        //DrawCard(1, 4);

        NextPhase();
    }
    public void ReadDeck()
    {
        //加载玩家卡组
        for (int i = 0; i < playerData.playerDeck.Length; i++)
        {
            if (playerData.playerDeck[i] != 0)
            {
                int count = playerData.playerDeck[i];
                for (int j = 0; j < count; j++)
                {
                    playerDeckList.Add(playerData.CardStore.CopyCard(i));
                    playerDeckList2.Add(playerData.CardStore.CopyCard(i));
                }
            }
        }
        //加载敌人卡组
        for (int i = 0; i < enemyData.playerDeck.Length; i++)
        {
            if (enemyData.playerDeck[i] != 0)
            {
                int count = enemyData.playerDeck[i];
                for (int j = 0; j < count; j++)
                {
                    enemyDeckList.Add(enemyData.CardStore.CopyCard(i));
                }
            }
        }
        //加载玩家1角色卡
        //加载玩家2角色卡
        //加载敌人角色卡
        CharacterCard randomPlayerCharacterCard = playerData.CardStore.RandomCharacterCard();
        CharacterCard randomPlayerCharacterCard2 = playerData.CardStore.RandomCharacterCard();
        if (randomPlayerCharacterCard != null && randomPlayerCharacterCard2 != null)
        {
            playerData.CharacterCard = randomPlayerCharacterCard;
            // 这里可以将角色卡信息绑定到UI或其他游戏逻辑中
            playerAttackTarget.SetCharacterCard(randomPlayerCharacterCard);
            playerIcon.GetComponent<CardDisplay>().card = randomPlayerCharacterCard;
            playerIcon.GetComponent<CardDisplay>().ShowCard();
            playerAttackTarget2.SetCharacterCard(randomPlayerCharacterCard2);
            playerIcon2.GetComponent<CardDisplay>().card = randomPlayerCharacterCard2;
            playerIcon2.GetComponent<CardDisplay>().ShowCard();
        }

        // 加载敌人角色卡
        CharacterCard randomEnemyCharacterCard = enemyData.CardStore.RandomCharacterCard();
        if (randomEnemyCharacterCard != null)
        {
            enemyData.CharacterCard = randomEnemyCharacterCard; // 更新敌人角色卡
            enemyAttackTarget.SetCharacterCard(randomEnemyCharacterCard);
            enemyIcon.GetComponent<CardDisplay>().card = randomEnemyCharacterCard;
            enemyIcon.GetComponent<CardDisplay>().ShowCard();
        }
        else
        {
            Debug.LogWarning("没有可用的敌人角色卡！");
        }
    }
    public void ShuffletDeck(int _player)//0为玩家，1为敌人
    {
        List<Card> shuffletDeck = new List<Card>();
        List<Card> shuffletDeck1 = new List<Card>();
        if (_player == 0)
        {
            shuffletDeck = playerDeckList;
        }
        else if (_player == 1)
        {
            shuffletDeck = enemyDeckList;
        }

        //洗牌算法，遍历卡组，随机卡牌交换位置
        for (int i = 0; i < shuffletDeck.Count; i++)
        {
            int rad = Random.Range(0, shuffletDeck.Count);

            Card temp = shuffletDeck[i];
            shuffletDeck[i] = shuffletDeck[rad];
            shuffletDeck[rad] = temp;
        }
    }
    public void ShuffletDeck1(int _player)//0为玩家，1为敌人
    {
        List<Card> shuffletDeck = new List<Card>();
        if (_player == 0)
        {
            shuffletDeck = playerDeckList2;
        }
        else if (_player == 1)
        {
            shuffletDeck = enemyDeckList;
        }

        //洗牌算法，遍历卡组，随机卡牌交换位置
        for (int i = 0; i < shuffletDeck.Count; i++)
        {
            int rad = Random.Range(0, shuffletDeck.Count);

            Card temp = shuffletDeck[i];
            shuffletDeck[i] = shuffletDeck[rad];
            shuffletDeck[rad] = temp;
        }
    }
    //抽卡算法
    public void DrawCard(int _player, int _count)
    {
        Transform hand = transform; // 给予初始值
        Transform hand2 = transform; // 给予初始值
        List<Card> drawDeck = null;
        List<Card> drawDeck2 = null;
        if (_player == 0)
        {
            drawDeck = playerDeckList;
            drawDeck2 = playerDeckList2;
            hand = playerHand;
            hand2 = playerHand2;
        }
        else if (_player == 1)
        {
            drawDeck = enemyDeckList;
            hand = enemyHand;
        }
        // 计算实际可抽的卡牌数量（不超过4张）
        if (_player == 0)
        {
            // 检查当前手牌数量是否已达到上限
            int currentHandCount = hand.childCount;
            if (currentHandCount >= 9)
            {
                Debug.Log("手牌已满");
            }
            int actualDrawCount = Mathf.Min(_count, 9 - currentHandCount);
            for (int i = 0; i < actualDrawCount; i++)
            {
                if (drawDeck.Count > 0) // 确保卡组中还有卡牌
                {
                    GameObject card = Instantiate(cardPrefab, hand);
                    card.transform.localPosition = Vector3.zero;
                    card.GetComponent<CardDisplay>().card = drawDeck[0];
                    card.GetComponent<BattleCard>().playerID = _player;
                    // 从卡组中移除卡牌
                    drawDeck.RemoveAt(0);
                }
                else
                {
                    ReloadDeck(_player);
                    GameObject card = Instantiate(cardPrefab, hand);
                    card.transform.localPosition = Vector3.zero;
                    card.GetComponent<CardDisplay>().card = drawDeck[0];
                    card.GetComponent<BattleCard>().playerID = _player;
                    // 从卡组中移除卡牌
                    drawDeck.RemoveAt(0);
                }
            }
            int currentHandCount2 = hand2.childCount;
            if (currentHandCount2 >= 9)
            {
                Debug.Log("手牌已满");
            }
            // 计算实际可抽的卡牌数量（不超过4张）
            int actualDrawCount2 = Mathf.Min(_count, 9 - currentHandCount2);
            for (int j = 0; j < actualDrawCount2; j++)
            {
                if (drawDeck2.Count > 0) // 确保卡组中还有卡牌
                {
                    GameObject card = Instantiate(cardPrefab, hand2);
                    card.transform.localPosition = Vector3.zero;
                    card.GetComponent<CardDisplay>().card = drawDeck2[0];
                    card.GetComponent<BattleCard>().playerID = _player;
                    // 从卡组中移除卡牌
                    drawDeck2.RemoveAt(0);
                }
                else
                {
                    ReloadDeck2(_player);
                    GameObject card = Instantiate(cardPrefab, hand2);
                    card.transform.localPosition = Vector3.zero;
                    card.GetComponent<CardDisplay>().card = drawDeck2[0];
                    card.GetComponent<BattleCard>().playerID = _player;
                    // 从卡组中移除卡牌
                    drawDeck2.RemoveAt(0);
                }
            }
        }
        else if (_player == 1)
        {
            // 检查当前手牌数量是否已达到上限
            int currentHandCount = hand.childCount;
            if (currentHandCount >= 9)
            {
                Debug.Log("手牌已满");
                return; // 如果手牌已满，则直接返回，不再抽卡
            }
            int actualDrawCount = Mathf.Min(_count, 9 - currentHandCount);
            for (int i = 0; i < actualDrawCount; i++)
            {
                if (drawDeck.Count > 0) // 确保卡组中还有卡牌
                {
                    GameObject card = Instantiate(cardPrefab, hand);
                    card.transform.localPosition = Vector3.zero;
                    card.GetComponent<CardDisplay>().card = drawDeck[0];
                    card.GetComponent<BattleCard>().playerID = _player;
                    // 从卡组中移除卡牌
                    drawDeck.RemoveAt(0);
                }
                else
                {
                    ReloadDeck(_player);
                }
            }
        }
    }
    public void OnClickTurnEnd()
    {
        TurnEnd();
    }
    public void TurnEnd()
    {
        //回合结束跳转抽卡
        if (GamePhase == GamePhase.playerAction || GamePhase == GamePhase.enemyAction)
        {
            NextPhase();
        }
    }
    //进入下个回合
    public void NextPhase()
    {
        // 枚举保存的是数字变量
        if ((int)GamePhase == System.Enum.GetNames(GamePhase.GetType()).Length - 1)
        {
            GamePhase = GamePhase.playerDraw;
        }
        else
        {
            GamePhase += 1;
        }

        // 在进入抽卡阶段前，将手牌全部移入弃牌堆
        if (GamePhase == GamePhase.playerDraw || GamePhase == GamePhase.enemyDraw)
        {
            DiscardAllCards(0); // 玩家弃牌
            DiscardAllCards(1); // 敌人弃牌
        }

        phaseChangeEvent.Invoke();

        if (GamePhase == GamePhase.enemyDraw)
        {
            DrawCard(1, 4);
            NextPhase();
            enemyData.RestoreMana();
            enemyIcon.GetComponent<CardDisplay>().ShowCard();

        }
        else if (GamePhase == GamePhase.enemyAction)
        {
            EnemyAutoPlay();  // 敌人自动出牌
            NextPhase();       // 立即进入下一阶段
        }
        else if (GamePhase == GamePhase.playerDraw)
        {
            DrawCard(0, 4);
            NextPhase();
            playerData.RestoreMana();
            playerIcon.GetComponent<CardDisplay>().ShowCard();
            playerIcon2.GetComponent<CardDisplay>().ShowCard();

        }
    }

    //将指定玩家的手牌全部移入弃牌堆
    public void DiscardAllCards(int _player)
    {
        Transform hand = null;          // 手牌容器
        Transform hand2 = null;          // 手牌容器
        List<Card> discardPile = null; // 弃牌堆
        List<Card> discardPile2 = null; // 弃牌堆
        if (_player == 0)
        {
            hand = playerHand;
            hand2 = playerHand2;
            discardPile = playerDiscardPile;
            discardPile2 = playerDiscardPile2;
        }
        else if (_player == 1)
        {
            hand = enemyHand;
            discardPile = enemyDiscardPile;
        }

        // 检查是否有手牌
        if (hand != null && hand.childCount > 0)
        {

            // 遍历手牌容器中的所有子对象
            foreach (Transform cardObject in hand)
            {
                CardDisplay cardDisplay = cardObject.GetComponent<CardDisplay>();
                if (cardDisplay != null && cardDisplay.card != null)
                {
                    // 将卡牌数据加入弃牌堆
                    discardPile.Add(cardDisplay.card);
                }

                // 销毁手牌对象
                Destroy(cardObject.gameObject);
            }
        }
        if (hand2 != null && hand2.childCount > 0)
        {
            // 遍历手牌容器中的所有子对象
            foreach (Transform cardObject in hand2)
            {
                CardDisplay cardDisplay = cardObject.GetComponent<CardDisplay>();
                if (cardDisplay != null && cardDisplay.card != null)
                {
                    // 将卡牌数据加入弃牌堆
                    discardPile2.Add(cardDisplay.card);
                }

                // 销毁手牌对象
                Destroy(cardObject.gameObject);
            }
        }
    }

    public void CreateArrow(Transform _startPoint, GameObject _prefab)
    {
        DestroyArrow();
        arrow = GameObject.Instantiate(_prefab, Canvas);

        arrow.GetComponent<Arrow>().SetStartPoint(new Vector2(_startPoint.position.x, _startPoint.position.y));

    }
    public void DestroyArrow()
    {
        Destroy(arrow);
    }
    public void CloseBlocks()
    {

        foreach (var block in playerBlocks)
        {
            block.GetComponent<Block>().AttackBlock.SetActive(false);//攻击显示
            //关闭显示，不然点击卡牌后会一直显示
        }
        foreach (var block in enemyBlocks)
        {
            block.GetComponent<Block>().AttackBlock.SetActive(false);//攻击显示
            //关闭显示，不然点击卡牌后会一直显示
        }
    }
    //攻击请求
    public void AttackRequst(int _player, GameObject _monster)
    {
        bool hasMonsterBlock = false;
        hasMonsterBlock = true;
        if (hasMonsterBlock)
        {
            attackingcard = _monster;
            attackingPlayer = _player;
            CreateArrow(_monster.transform, attackArrow);
        }
        else
        {
            Debug.LogWarning("没有可攻击的目标！");
        }
        if (attackingcard.GetComponent<CardDisplay>().card is AttackCard)
        {
            targetenemyopen();
        }
        else if (attackingcard.GetComponent<CardDisplay>().card is ShieldCard)
        {
            targetplayeropen();
        }
        else if (attackingcard.GetComponent<CardDisplay>().card is SpellCard)
        {
            targetplayeropen();
        }
    }
    //攻击确认
    public void AttackConfirm(GameObject _target)
    {
        // ================= 防御性编程增强 =================
        if (_target == null)
        {
            Debug.LogError("攻击目标为空！");
            return;
        }

        if (attackingcard == null)
        {
            Debug.LogError("攻击者对象为空！");
            return;
        }

        // 缓存卡牌组件（优化性能）
        CardDisplay cardDisplay = attackingcard.GetComponent<CardDisplay>();
        if (cardDisplay == null || cardDisplay.card == null)
        {
            Debug.LogError("攻击卡牌数据异常");
            return;
        }
        Card card = cardDisplay.card;

        // ================= 分支逻辑优化 =================
        bool isAttackCard = card is AttackCard;
        bool isShieldCard = card is ShieldCard;
        bool isSpellCard = card is SpellCard;

        // 使用 if-else 链确保单一执行路径
        if (isAttackCard)
        {
            Attack(attackingcard, _target);
            targetenemyclose();
        }
        else if (isShieldCard)
        {
            Shield(attackingcard, _target);
            targetplayerclose();
        }
        else if (isSpellCard)
        {
            HandleSpellCard(card as SpellCard, _target);
            targetplayerclose();
        }
        else
        {
            Debug.LogWarning($"未知卡牌类型: {card.GetType()}");
        }

        // ================= 后处理 =================
        DestroyArrow();
        CloseBlocks();

        // 重置攻击状态（新增）
        attackingcard = null;
        attackingPlayer = -1;
    }

    // ================= 提取法术卡处理逻辑 =================
    private void HandleSpellCard(SpellCard spellCard, GameObject target)
    {
        if (spellCard == null) return;

        // 使用 switch 提高可读性（注意C#字符串比较方式）
        switch (spellCard.cardName)
        {
            case "回血":
                Regainhealth(attackingcard, target);
                break;
            case "回蓝":
                Regainmana(attackingcard, target);
                break;
            case "抽卡":
                Drawonecard(attackingcard, target);
                break;
            default:
                Debug.LogWarning($"未知法术卡: {spellCard.cardName}");
                break;
        }
    }
    public void Attack(GameObject _attacker, GameObject _target)
    {
        if (_attacker == null)
        {
            Debug.LogError("攻击者对象为空！");
            return;
        }
        AttackCard attackcard = _attacker.GetComponent<CardDisplay>().card as AttackCard;
        _target.GetComponent<AttackTarget>().ApplyDamage(attackcard.attack);
        _attacker.GetComponent<BattleCard>().CostAttackCount();
        _target.GetComponent<CardDisplay>().ShowCard();
    }
    public void Shield(GameObject _attacker, GameObject _target)
    {
        if (_attacker == null)
        {
            Debug.LogError("护盾加持者对象为空！");
            return;
        }
        ShieldCard shieldcard = _attacker.GetComponent<CardDisplay>().card as ShieldCard;
        _target.GetComponent<AttackTarget>().ApplyShield(shieldcard.Shield);
        _attacker.GetComponent<BattleCard>().CostAttackCount();
        _target.GetComponent<CardDisplay>().ShowCard();
    }
    public void Regainhealth(GameObject _attacker, GameObject _target)
    {
        if (_attacker == null)
        {
            Debug.LogError("回复血量的对象为空！");
            return;
        }
        SpellCard Regainhealthcard = _attacker.GetComponent<CardDisplay>().card as SpellCard;
        _target.GetComponent<AttackTarget>().ApplyRegainhealth(Regainhealthcard.effectvalue);
        _attacker.GetComponent<BattleCard>().CostAttackCount();
        _target.GetComponent<CardDisplay>().ShowCard();
    }
    public void Regainmana(GameObject _attacker, GameObject _target)
    {
        if (_attacker == null)
        {
            Debug.LogError("回复蓝量的对象为空！");
            return;
        }
        SpellCard Regainmana = _attacker.GetComponent<CardDisplay>().card as SpellCard;
        _target.GetComponent<AttackTarget>().ApplyRegainmana(Regainmana.effectvalue);
        _attacker.GetComponent<BattleCard>().CostAttackCount();
        _target.GetComponent<CardDisplay>().ShowCard();
    }
    public void Drawonecard(GameObject _attacker, GameObject _target)
    {
        if (_attacker == null)
        {
            Debug.LogError("卡组已满");
            return;
        }
        if (attackingPlayer == 0)
        {
            DrawCard(0, 1);
            Destroy(_attacker.gameObject);
        }
        if (attackingPlayer == 1)
        {
            DrawCard(1, 1);
            Destroy(_attacker.gameObject);
        }
    }
    //弃牌堆的实现
    // 重新加载卡组的方法
    public void ReloadDeck(int _player)
    {
        List<Card> discardPile = null; // 弃牌堆
        List<Card> targetDeck = null;  // 卡组

        if (_player == 0)
        {
            discardPile = playerDiscardPile; // 玩家的弃牌堆
            targetDeck = playerDeckList;    // 玩家的卡组
        }
        else if (_player == 1)
        {
            discardPile = enemyDiscardPile; // 敌人的弃牌堆
            targetDeck = enemyDeckList;     // 敌人的卡组
        }

        // 检查弃牌堆是否为空
        if (discardPile == null || discardPile.Count <= 0)
        {
            Debug.LogWarning($"玩家 {_player} 的弃牌堆为空，无法重新加载卡组！");
            return;
        }
        Debug.Log($"重新加载玩家 {_player} 的卡组...");

        // 将弃牌堆中的所有卡牌移入卡组
        targetDeck.AddRange(discardPile);
        discardPile.Clear(); // 清空弃牌堆
        // 打乱卡组顺序
        ShuffletDeck(_player);

        Debug.Log($"玩家 {_player} 的卡组已重新加载并洗牌！");
    }
    public void ReloadDeck2(int _player)
    {
        List<Card> discardPile = null; // 弃牌堆
        List<Card> targetDeck = null;  // 卡组

        if (_player == 0)
        {
            discardPile = playerDiscardPile2;
            targetDeck = playerDeckList2;    // 玩家的卡组
        }
        else if (_player == 1)
        {
            discardPile = enemyDiscardPile; // 敌人的弃牌堆
            targetDeck = enemyDeckList;     // 敌人的卡组
        }

        // 检查弃牌堆是否为空
        if (discardPile == null || discardPile.Count <= 0)
        {
            Debug.LogWarning($"玩家 {_player} 的弃牌堆为空，无法重新加载卡组！");
            return;
        }

        Debug.Log($"重新加载玩家 {_player} 的卡组...");

        // 将弃牌堆中的所有卡牌移入卡组
        targetDeck.AddRange(discardPile);
        discardPile.Clear(); // 清空弃牌堆

        // 打乱卡组顺序
        ShuffletDeck1(_player);

        Debug.Log($"玩家 {_player} 的卡组已重新加载并洗牌！");
    }
    //敌方可点击性开启
    public void targetenemyopen()
    {
        GameObject[] blocks;
        if (attackingPlayer == 0 && GamePhase == GamePhase.playerAction)
        {
            blocks = enemyBlocks;
        }
        else if (attackingPlayer == 1 && GamePhase == GamePhase.enemyAction)
        {
            blocks = playerBlocks;
        }
        else
        {
            Debug.Log("当前阶段不允许攻击！");
            DestroyArrow();
            return;
        }

        foreach (var block in blocks)
        {
            if (block.GetComponent<Block>().card != null)
            {
                block.GetComponent<Block>().AttackBlock.SetActive(true);
                //等待攻击显示
                block.GetComponent<Block>().card.GetComponent<AttackTarget>().attackable = true;
            }
        }
    }
    //我方可点击性开启
    public void targetplayeropen()
    {
        GameObject[] blocks;
        if (attackingPlayer == 0 && GamePhase == GamePhase.playerAction)
        {
            blocks = playerBlocks;
        }
        else if (attackingPlayer == 1 && GamePhase == GamePhase.enemyAction)
        {
            blocks = enemyBlocks;
        }
        else
        {
            Debug.Log("当前阶段不允许攻击！");
            DestroyArrow();
            return;
        }

        foreach (var block in blocks)
        {
            if (block.GetComponent<Block>().card != null)
            {
                block.GetComponent<Block>().AttackBlock.SetActive(true);
                //等待攻击显示
                block.GetComponent<Block>().card.GetComponent<AttackTarget>().attackable = true;
            }
        }
    }
    //敌方可点击性关闭
    public void targetplayerclose()
    {
        GameObject[] blocks;
        if (attackingPlayer == 0)
        {
            blocks = enemyBlocks;
        }
        else
        {
            blocks = playerBlocks;
        }
        foreach (var block in blocks)
        {
            if (block.GetComponent<Block>().card != null)
            {
                block.GetComponent<Block>().card.GetComponent<AttackTarget>().attackable = false;
            }
        }
    }
    //我方可点击性关闭
    public void targetenemyclose()
    {
        GameObject[] blocks;
        if (attackingPlayer == 0)
        {
            blocks = playerBlocks;
        }
        else
        {
            blocks = enemyBlocks;
        }
        foreach (var block in blocks)
        {
            if (block.GetComponent<Block>().card != null)
            {
                block.GetComponent<Block>().card.GetComponent<AttackTarget>().attackable = false;
            }
        }
    }
    // 在BattleManager类中添加以下方法
    private void EnemyAutoPlay()
    {
        // 复制手牌列表避免修改集合时的遍历问题
        List<Transform> cardsToPlay = new List<Transform>();
        foreach (Transform cardTransform in enemyHand)
        {
            cardsToPlay.Add(cardTransform);
        }

        foreach (Transform cardTransform in cardsToPlay)
        {
            BattleCard battleCard = cardTransform.GetComponent<BattleCard>();
            CardDisplay cardDisplay = cardTransform.GetComponent<CardDisplay>();
            Card card = cardDisplay.card;

            // 检查法力是否足够
            if (enemyData.CharacterCard.mana >= card.mana)
            {
                // 扣除法力
                enemyData.CharacterCard.mana -= card.mana;

                // 根据卡牌类型处理
                if (card is AttackCard attackCard)
                {
                    // 创建可能的目标列表
                    List<GameObject> validTargets = new List<GameObject>();
                    if (playerIcon.activeInHierarchy) validTargets.Add(playerIcon);
                    if (playerIcon2.activeInHierarchy) validTargets.Add(playerIcon2);

                    // 如果有存活目标才攻击
                    if (validTargets.Count > 0)
                    {
                        int randomIndex = Random.Range(0, validTargets.Count);
                        AttackDirectly(cardTransform.gameObject, validTargets[randomIndex]);
                    }
                }
                else if (card is ShieldCard shieldCard)
                {
                    // 给敌方角色添加护盾
                    ApplyShield(enemyIcon, shieldCard.Shield);
                }
                else if (card is SpellCard spellCard)
                {
                    if (card.cardName is "回血")
                    {
                        ApplyRegainhealth(enemyIcon, spellCard.effectvalue);
                    }
                    else if (card.cardName is "回蓝")
                    {
                        ApplyRegainmana(enemyIcon, spellCard.effectvalue);
                    }
                }

                // 加入弃牌堆并销毁手牌对象
                enemyDiscardPile.Add(card);
                Destroy(cardTransform.gameObject);
            }
        }
    }

    // 直接攻击方法
    private void AttackDirectly(GameObject cardObject, GameObject target)
    {
        if (target == null || !target.activeInHierarchy)
        {
            // 如果目标不存在，从存活目标中重新选择
            List<GameObject> aliveTargets = new List<GameObject>();
            if (playerIcon.activeInHierarchy) aliveTargets.Add(playerIcon);
            if (playerIcon2.activeInHierarchy) aliveTargets.Add(playerIcon2);

            if (aliveTargets.Count == 0) return;

            int randomIndex = Random.Range(0, aliveTargets.Count);
            target = aliveTargets[randomIndex];
        }

        AttackCard attackCard = cardObject.GetComponent<CardDisplay>().card as AttackCard;
        if (attackCard != null && target != null)
        {
            target.GetComponent<AttackTarget>().ApplyDamage(attackCard.attack);
            //Debug.Log($"敌人使用【{attackCard.cardName}】对你造成{attackCard.attack}点伤害！");
            target.GetComponent<CardDisplay>().ShowCard();
        }
    }

    // 护盾施加方法
    private void ApplyShield(GameObject target, int shieldValue)
    {
        if (target != null)
        {
            target.GetComponent<AttackTarget>().ApplyShield(shieldValue);
            //Debug.Log($"敌人获得{shieldValue}点护盾！");
            target.GetComponent<CardDisplay>().ShowCard();
        }
    }
    private void ApplyRegainhealth(GameObject target, int effectvalue)
    {
        if (target != null)
        {
            target.GetComponent<AttackTarget>().ApplyRegainhealth(effectvalue);
            //Debug.Log($"敌人回复{effectvalue}点血量！");
            target.GetComponent<CardDisplay>().ShowCard();
        }
    }

    private void ApplyRegainmana(GameObject target, int effectvalue)
    {
        if (target != null)
        {
            target.GetComponent<AttackTarget>().ApplyRegainmana(effectvalue);
            //Debug.Log($"敌人回复{effectvalue}点蓝量！");
            target.GetComponent<CardDisplay>().ShowCard();
        }
    }

}
